import axios from 'axios';
import PromiseState from './promiseState';

const config = {
  APIFormat: 'h5proxy',
};
// const dev = 'http://localhost:3001';
const online = '';
const API = axios.create({
  timeout: 15 * 1000,
  contentType: 'application/json',
  baseURL: dev,
  headers: {
    'Content-Type': 'application/json',
  },
});
API.interceptors.request.use((config) => {
  const token = window.localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`; // 将token放到请求头发送给服务器
  }
  return config;
});
export default {
  methods: {
    newStore() {
      return new PromiseState();
    },
    spost(store, path, data) {
      return new Promise((resolve, reject) => {
        store.b = new Date();
        store.t = 'ajax';
        store.u = path;
        store.r = data;
        store.p = true;
        store.o = false;
        store.e = false;
        store.m = '';
        store.d = {};
        store.s += 1;
        data = ({
          ...data,
        }) || {};
        let post;
        switch (config.APIFormat) {
          case 'h5proxy':
            post = API.post(path, data);
            break;
          default:
            alert(`no APIFormat ${config.APIFormat}`);
            return;
        }
        post
          .then((res) => {
            const d = res.data;
            store.f = new Date();
            store.p = false;
            store.c = parseInt(d.status, 10);
            store.d = d;
            if (store.c === 200) {
              store.o = true;
              store.e = false;
              store.m = d.resultMsg || "";
              resolve(store);
            } else {
              store.o = false;
              store.e = true;
              store.m = d.message || '';
              reject(store);
            }
            this.$emit(`ajax:${store.u}`, store);
          })
          .catch((d) => {
            store.f = new Date();
            store.p = false;
            store.o = false;
            store.e = true;
            store.c = -2;
            if (d.response.status === 500) {
              store.m = '服务器异常';
              this.$message({
                message: d.response.data.message || '服务器异常',
                type: 'error',
              });
            } else if (d.response.status === 401) {
              this.$confirm('您尚未登录或者登录失效, 该功能需要登录，是否跳转登录界面？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false,
              }).then(() => {
                this.$router.push('/login');
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消',
                });
              });
              store.m = "token失效";
            } else {
              store.m = d.response.data.message || '服务调用异常';
              this.$message({
                message: d.response.data.message || '服务器异常',
                type: 'error',
              });
            }
            store.d = d;
            this.$emit(`ajax:${store.u}`, store);
            reject(store);
          });
      });
    },
  },
};
